package cn.aspart.validation.util;

import cn.hutool.json.JSONUtil;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;

import java.util.List;
import java.util.Set;

public class ValidationUtil {
    private static final Validator VALIDATOR;

    static {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        VALIDATOR = factory.getValidator();
    }

    /**
     * 验证一个实体是否符合验证规则
     *
     * @param object 被验证实体
     * @return Boolean
     */
    public static Boolean validate(Object object) {
        Set<ConstraintViolation<Object>> violations = VALIDATOR.validate(object);
        System.out.println(JSONUtil.toJsonPrettyStr(violations));
        return violations == null || violations.size() < 1;
    }

    /**
     * 验证一个集合中所有实例
     *
     * @param list 需要验证的集合
     * @return Boolean
     */
    public static Boolean validate(List list) {
        for (Object o : list) {
            if (!validate(o)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 分组验证一个实体是否符合验证规则
     *
     * @param object 被验证实体
     * @param groups 分组类
     * @return Boolean
     */
    public static Boolean validate(Object object, Class... groups) {
        Set<ConstraintViolation<Object>> violations = VALIDATOR.validate(object, groups);
        //        if (violations == null || violations.size() < 1) {
        //            return true;
        //        }
        //
        //        StringBuilder sb = new StringBuilder();
        //        violations.forEach(violation -> {
        //            sb.append(" ").append(violation.getMessage());
        //        });
        //        System.out.println(sb.toString());
        //        log.debug(sb.toString());
        //        return false;
        return violations == null || violations.size() < 1;
    }
}
